import 'dart:convert';
import 'dart:math';
import 'package:cbec_app/pages/main/controller/main_ctr.dart';
import 'package:cbec_app/utils/AppData.dart';
import 'package:flutter/services.dart';
import 'package:flutter/material.dart';
import 'package:cbec_app/components/base/base_icon.dart';
import 'package:cbec_app/components/base/base_interactive.dart';
import 'package:cbec_app/components/common/common_style.dart';
import 'package:cbec_app/routes/routes.dart';
import 'package:cbec_app/utils/EventMgr.dart';
import 'package:cbec_app/utils/ThemeConfig.dart';
import 'package:cbec_app/utils/cache_mgr.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../pages/classify/binding/brand_detail_binding.dart';
import '../pages/classify/view/brand_detail.dart';
import '../pages/goods/binding/goods_detail_binding.dart';
import '../pages/goods/view/goods_detail_page.dart';
import 'package:crypto/crypto.dart';
import 'package:uuid/uuid.dart';

///工具类函数
class Tools {
  Tools._();

  ///转换hex颜色值
  /// 转换 hex 或 rgba 颜色值
  static Color fromHex(String hexString) {
    if (hexString == 'transparent') {
      return Colors.transparent;
    }
    if (hexString == '') {
      return Colors.white;
    }
    // 解析 rgba
    if (hexString.contains('rgba')) {
      List<String> parts = hexString.replaceAll('rgba(', '').replaceAll(')', '').split(',');
      return Color.fromRGBO(
        int.parse(parts[0].toString()), // alpha
        int.parse(parts[1].toString()), // red
        int.parse(parts[2].toString()), // green
        double.parse(parts[3].toString()), // blue
      );
    }
    final buffer = StringBuffer();
    if (hexString.length == 4) {
      hexString += hexString.split('#')[1];
    }
    if (hexString.length == 6 || hexString.length == 7) {
      buffer.write('ff');
    }
    buffer.write(hexString.replaceFirst('#', ''));
    return Color(int.parse(buffer.toString(), radix: 16));
  }

  ///转化字重
  static FontWeight cssFontWeightToFlutter(String cssFontWeight) {
    switch (cssFontWeight) {
      case 'normal':
        return FontWeight.normal;
      case 'bold':
        return FontWeight.bold;
      case 'lighter':
        return FontWeight.w300;
      case 'bolder':
        return FontWeight.w700;
      default:
        return getWeight(cssFontWeight);
    }
  }

  ///获取css字重对应的flutter字重
  static FontWeight getWeight(String cssFontWeight) {
    FontWeight weight = FontWeight.w300;
    int cssWeight = int.parse(cssFontWeight) + 50;
    for (var item in FontWeight.values) {
      if (item.toString().contains(cssFontWeight)) {
        weight = item;
        break;
      } else if (item.toString().contains(cssWeight.toString())) {
        weight = item;
        break;
      }
    }
    return weight;
  }

  ///获取设备信息
  static getDeviceInfo() async {
    DeviceInfoPlugin deviceInfoPlugin = DeviceInfoPlugin();
    var deviceInfo = await deviceInfoPlugin.deviceInfo;
    var allInfo = deviceInfo.data;
    return allInfo;
  }

  ///显示toast
  static void showToast(String msg, {Duration duration = const Duration(milliseconds: 2500)}) async {
    SmartDialog.showToast(msg, alignment: Alignment.center, debounce: true, displayTime: duration);
  }

  ///基础对话框
  ///isSingleBtn 是否为单按钮形式，当为true时，按钮设置和回调均以confirm的参数为准
  static _showBaseModal({String title = '温馨提示', Widget? content, String? tag, String cancelText = '取消', String confirmText = '确定', bool isSingleBtn = false, VoidCallback? onConfirm, VoidCallback? onCancel}) {
    SmartDialog.show(
        tag: tag,
        alignment: Alignment.center,
        debounce: true,
        builder: (context) {
          return UnconstrainedBox(
            child: Container(
              width: 320.w,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(8),
              ),
              alignment: Alignment.center,
              child: Column(
                children: [
                  //标题
                  Padding(padding: const EdgeInsets.only(top: 32, bottom: 32), child: Text(title, style: setTextStyle(17, FontWeight.bold, ThemeConfig.boldTextColor))),
                  //内容
                  content ?? emptyWidget(),
                  //按钮
                  isSingleBtn
                      ? BaseInteractive(
                          childWidget: Container(
                            alignment: Alignment.center,
                            decoration: const BoxDecoration(border: Border(top: BorderSide(color: ThemeConfig.divideColor, width: 0.5))),
                            height: 56.h,
                            child: Text(
                              confirmText,
                              style: setTextStyle(17, FontWeight.bold, Color(0xff576B95)),
                            ),
                          ),
                          onClick: () {
                            if (onConfirm != null) {
                              onConfirm();
                            }
                          },
                        )
                      : Container(
                          decoration: const BoxDecoration(border: Border(top: BorderSide(color: ThemeConfig.divideColor, width: 0.5))),
                          height: 56.h,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              BaseInteractive(
                                childWidget: Container(
                                  width: 160.w,
                                  height: 56.h,
                                  alignment: Alignment.center,
                                  child: Text(
                                    cancelText,
                                    style: setTextStyle(17, FontWeight.bold, ThemeConfig.boldTextColor),
                                  ),
                                ),
                                onClick: () {
                                  if (onCancel != null) {
                                    onCancel();
                                  }
                                },
                              ),
                              BaseInteractive(
                                childWidget: Container(
                                  width: 160.w,
                                  height: 56.h,
                                  alignment: Alignment.center,
                                  child: Text(
                                    confirmText,
                                    style: setTextStyle(17, FontWeight.bold, Color(0xff576B95)),
                                  ),
                                ),
                                onClick: () {
                                  if (onConfirm != null) {
                                    onConfirm();
                                  }
                                },
                              )
                            ],
                          ),
                        )
                ],
              ),
            ),
          );
        });
  }

  ///普通对话框
  ///title 弹框标题 content 弹框内容（可为普通文本或富文本） onConfirm 确定按钮回调 onCancel 取消按钮回调
  ///isAutoClose 点击取消是否自动关闭
  static showModal({String title = '温馨提示', String? content, bool isRichText = false, Widget? richText, bool isAutoClose = true, String cancelText = '取消', String confirmText = '确定', Function(String tag)? onConfirm, Function(String tag)? onCancel}) {
    _showBaseModal(
      tag: 'normal',
      title: title,
      cancelText: cancelText,
      confirmText: confirmText,
      content: isRichText
          ? Container(
              padding: const EdgeInsets.only(left: 24, right: 24, bottom: 20),
              child: richText,
            )
          : Container(
              padding: const EdgeInsets.only(left: 24, right: 24, bottom: 20),
              child: Text(
                content!,
                style: setTextStyle(17, FontWeight.w300, ThemeConfig.boldTextColor),
              ),
            ),
      onCancel: () {
        if (isAutoClose) {
          SmartDialog.dismiss(tag: 'normal');
        }
        if (onCancel != null) {
          onCancel('normal');
        }
      },
      onConfirm: () {
        if (onConfirm != null) {
          onConfirm('normal');
        }
      },
    );
  }

  ///带输入框的对话框
  static showInputModal({String title = '转账说明', String? content, String? placeholder = '收款方可见，最多10个字', bool isAutoClose = true, Function(String value)? onInput, Function(String tag)? onConfirm, Function(String tag)? onCancel}) {
    _showBaseModal(
      tag: 'input',
      title: title,
      content: Container(
        padding: const EdgeInsets.only(left: 24, right: 24, bottom: 20),
        child: CupertinoTextField(
          inputFormatters: [
            FilteringTextInputFormatter.allow(RegExp("[a-zA-Z]|[\u4e00-\u9fa5]|[0-9]")), //只能输入汉字或者字母或数字
          ],
          placeholder: placeholder,
          decoration: const BoxDecoration(border: Border(bottom: BorderSide(color: ThemeConfig.divideColor, width: 0.5))),
          maxLength: 10,
          placeholderStyle: setTextStyle(15, FontWeight.w300, ThemeConfig.sectionTextColor),
          style: setTextStyle(17, FontWeight.w300, ThemeConfig.boldTextColor),
          onChanged: (value) {
            if (onInput != null) {
              onInput(value);
            }
          },
        ),
      ),
      onCancel: () {
        if (isAutoClose) {
          SmartDialog.dismiss(tag: 'input');
        }
        if (onCancel != null) {
          onCancel('input');
        }
      },
      onConfirm: () {
        if (onConfirm != null) {
          onConfirm('input');
        }
      },
    );
  }

  ///仅提示信息的输入框
  static showInfoModal({String title = '温馨提示', String confirmText = '我知道了', Widget? content}) {
    _showBaseModal(
      title: title,
      content: content,
      confirmText: confirmText,
      tag: 'info',
      isSingleBtn: true,
      onConfirm: () {
        SmartDialog.dismiss(tag: 'info');
      },
    );
  }

  ///显示弹框广告
  static showDialogAd(Widget child) {
    SmartDialog.show(
      alignment: Alignment.center,
      debounce: false,
      clickMaskDismiss: false,
      builder: (context) {
        return Container(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              child,
              Container(
                margin: EdgeInsets.only(top: 71.h),
                child: BaseInteractive(
                  childWidget: BaseIcon(
                    url: 'close.png',
                    color: Colors.white,
                  ),
                  onClick: () {
                    SmartDialog.dismiss();
                  },
                ),
              )
            ],
          ),
        );
      },
    );
  }

  ///显示loading
  static showLoading({String title = '请稍候...'}) {
    EasyLoading.show(status: '请稍候...', maskType: EasyLoadingMaskType.black);
  }

  ///隐藏loading
  static hideLoading() {
    EasyLoading.dismiss();
  }

  ///手机号加密中间四位
  static String encryptPhoneNumber(String phoneNumber) {
    if (phoneNumber.length != 11) {
      // throw Exception("手机号长度必须为11位");
      return phoneNumber;
    }
    String encryptedPhoneNumber = phoneNumber.replaceRange(3, 7, '****');
    return encryptedPhoneNumber;
  }

  ///手机号校验
  static bool checkPhone(String phoneNumber) {
    // 中国手机号正则表达式
    RegExp mobileRegExp = RegExp(r'^1[2,3,4,5,6,7,8,9][0-9]{9}$');
    if (mobileRegExp.hasMatch(phoneNumber)) {
      return true;
    } else {
      return false;
    }
  }

  ///非空字符校验
  static bool checkEmpty(String value) {
    if (value == '') {
      return false;
    }
    return true;
  }

  ///校验字符串相等性
  static bool checkEqual(String value1, String value2) {
    if (!checkEmpty(value1) || !checkEmpty(value2)) {
      return false;
    }
    if (value1 != value2) {
      return false;
    }
    return true;
  }

  /// 获取文字信息
  static TextPainter getTextInfo({required BuildContext context, required String text, required TextStyle style, int maxLines = 2 ^ 23, double width = double.infinity, String? ellipsis, textDirection = TextDirection.LTR}) {
    TextSpan span = TextSpan(text: text, style: style);
    return TextPainter(
      locale: Localizations.localeOf(context),
      text: span,
      maxLines: maxLines,
      ellipsis: ellipsis,
      textDirection: textDirection,
    )..layout(maxWidth: width);
  }

  ///处理优惠券显示日期 yyyy-mm-dd - yyyy-mm-dd
  static String getCouponDate(String date) {
    var arr = date.split(' ');
    return '${arr[0]} - ${arr[3]}';
  }

  ///获取运输类型
  static String getTransportType(int type) {
    String txt = "";
    switch (type) {
      case 0:
        txt = "快递";
        break;
      case 1:
        txt = "同城配送";
        break;
      case 2:
        txt = "自提";
        break;
      default:
        txt = "未知";
    }
    return txt;
  }

  static String getRandomString(int length) {
    const chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
    final random = Random();
    return List.generate(length, (index) => chars[random.nextInt(chars.length)]).join();
  }

  ///获取支付类型
  static String getPaymentType(int type) {
    String txt = "";
    switch (type) {
      case 1:
        txt = "微信";
        break;
      case 2:
        txt = "支付宝";
        break;
      case 3:
        txt = "现金";
        break;
      case 4:
        txt = "预付卡";
        break;
      case 5:
        txt = "混合支付";
        break;
      case 6:
        txt = "银行卡";
        break;
      case 7:
        txt = "云闪付";
        break;
      default:
        txt = "未知";
    }
    return txt;
  }

  static Widget getPullRefresh({
    required RefreshController refreshController,
    bool enablePullDown = false,
    bool enablePullUp = false,
    void Function()? onRefresh,
    void Function()? onLoading,
    Widget? child,
  }) {
    return SmartRefresher(
      controller: refreshController,
      enablePullDown: enablePullDown, // 下拉刷新
      enablePullUp: enablePullUp, // 上拉加载
      onRefresh: onRefresh,
      onLoading: onLoading,
      header: const WaterDropHeader(
        refresh: SizedBox(
          width: 20,
          height: 20,
          child: CircularProgressIndicator(
            color: Colors.grey,
            strokeWidth: 2.0,
          ),
        ),
        complete: Center(child: Text('下拉刷新完成')),
      ),
      footer: const ClassicFooter(
        loadingIcon: SizedBox(
          width: 20,
          height: 20,
          child: CircularProgressIndicator(
            color: Colors.grey,
            strokeWidth: 2.0,
          ),
        ),
        canLoadingText: '上拉加载更多',
        loadingText: '加载中,请稍候...',
        idleText: '上拉加载更多',
        noDataText: '没有更多数据',
      ),
      child: child,
    );
  }

  ///跳转页面
  static void jumpPage(Map<String, dynamic> item) {
    print('/跳转页面item === $item');
    print('/跳转页面link_type 类型 --- ${item['link_type'].runtimeType}');
    print('/跳转页面link_id 类型 ---- ${item['link_id'].runtimeType}');

    var linkId = item['link_id'];
    if (linkId is String) {
      linkId = int.tryParse(linkId) ?? 0; // 如果转换失败，使用默认值0
    }
    switch (item['link_type']) {
      case '1': //跳基础页面
        {
          switch (linkId) {
            case 2: //分类
              if (Get.currentRoute.contains(Routes.microIndex)) {
                print('上面');
                //微页面
                Get.until((route) => Get.currentRoute == Routes.main);
                EventMgr.send(EventType.exchangeNav, MainController.mainBottomNavRouteNameClassify);
              } else {
                print('下面');
                //首页
                EventMgr.send(EventType.exchangeNav, MainController.mainBottomNavRouteNameClassify);
              }
              break;
            case 3: //领券中心
              Get.toNamed(Routes.couponCenter);
              break;
            case 4: //秒杀活动列表
              Get.toNamed(Routes.killSalesPage);
              break;
            case 5: //拼团活动列表
              Get.toNamed(Routes.groupBuyingPage);
              break;
            case 6: //砍价活动列表
              Get.toNamed(Routes.bargainingPage);
              break;
            case 7: //预售活动列表
              Get.toNamed(Routes.preSales);
              break;
            case 8: //特价
              Get.toNamed(Routes.discountGoodsList);
              break;
            case 9: //红包中心
              Get.toNamed(Routes.redpackMarket);
              break;
            case 10: //新品榜单
              Get.toNamed(Routes.newProductsRanking);
              break;
            case 11: //保税好价
              Get.toNamed(Routes.bondedGoodDeals);
              break;
            case 12: //天天补贴
              Get.toNamed(Routes.dailySubsidy);
              break;
            case 1: //首页
            default:
              Get.until((route) => Get.currentRoute == Routes.main);
              break;
          }
        }
        break;
      case '2': //跳转微页面
        print('是不是走的这里');
        Map<String, dynamic> params = {};
        params['id'] = item['link_id'];
        params['title'] = item['link_title'];
        // Get.toNamed(Routes.secondaryMicro, arguments: params);
        Get.toNamed('${Routes.secondaryMicro}?unique=${DateTime.now().millisecondsSinceEpoch}', arguments: params);
        break;
      case '3': //跳转商品详情
        final id = item['link_id'].toString();
        Get.to(
          () => GoodsDetailPage(flag: id), // 使用函数懒加载页面实例
          routeName: '${Routes.goodsDetail}?unique=${DateTime.now().millisecondsSinceEpoch}',
          arguments: {"id": id}, // 传递其它参数
          binding: GoodsDetailBinding(flag: id), // 将 tag 参数传递给绑定类
        );
        break;
      case '5': //跳转专题页面
        Map<String, dynamic> params = {};
        params['id'] = item['link_id'];
        params['title'] = item['link_title'];
        Get.toNamed(Routes.specialTopicPage, arguments: params);
        break;
      case '6': //品牌
        final id = item['link_id'] is String ? item['link_id'] : item['link_id'].toString();
        Get.to(
          () => BrandDetail(flag: id), // 使用函数懒加载页面实例
          routeName: '${Routes.brandDtail}?unique=${DateTime.now().millisecondsSinceEpoch}',
          arguments: {"id": id}, // 传递其它参数
          binding: BrandDetailBinding(flag: id), // 将 tag 参数传递给绑定类
        );

        break;
      case '7': //跳转分类筛选页
        List<String> targetIds = item['link_id'].toString().split('-');
        Get.toNamed('${Routes.filter}/?secondId=${targetIds[1]}&id=${targetIds[2]}');
        break;
      case '8': //秒杀活动
        Get.toNamed(Routes.killSalesPage);
        break;
      case '9': //拼团活动
        Get.toNamed(Routes.groupBuyingPage);
        break;
      case '10': //砍价活动
        Get.toNamed(Routes.bargainingPage);
        break;
      case '11': //预售活动
        Get.toNamed(Routes.preSales);
        break;
      case '12': //特价
        Get.toNamed(Routes.discountGoodsList);
        break;
      case '13': //新品榜单
        Get.toNamed(Routes.newProductsRanking);
        break;
      case '14': //保税好价
        Get.toNamed(Routes.bondedGoodDeals);
        break;
      case '15': //天天补贴
        Get.toNamed(Routes.dailySubsidy);
        break;
      default:
        break;
    }
  }

  ///获取装修图片缩放比例
  static double getImgScale(List dataList) {
    if (dataList.isEmpty || dataList == null) {
      return 1;
    }
    List<double> arr = [];
    for (var element in dataList) {
      double scale = element['image_width'] / element['image_height'];
      arr.add(scale);
    }
    arr.sort((a, b) {
      return b.compareTo(a);
    });
    return arr[0];
  }

  ///设置搜索历史
  static void setSearchHistory(String value) {
    if (value == '') {
      return;
    }
    List<String> arr = getSearchHistory();
    List<String> brr = [];
    if (arr.isEmpty) {
      //未存值时
      brr.add(value);
      CacheMgr.setStringList('searchHistory', brr);
    } else {
      //非空时判断重复
      bool isRepeat = false;
      for (var item in arr) {
        brr.add(item);
        if (value == item) {
          isRepeat = true;
          break;
        }
      }
      if (!isRepeat) {
        brr.insert(0, value);
        CacheMgr.setStringList('searchHistory', brr);
      }
    }
  }

  ///获取搜索历史
  static List<String> getSearchHistory() {
    List<String> arr = CacheMgr.getStringList('searchHistory');
    return arr.length > 12 ? arr.sublist(0, 12) : arr;
  }

  ///清空搜索历史
  static void clearSearchHistory() {
    CacheMgr.setStringList('searchHistory', []);
  }

  /// 验证给定的手机号码是否有效
  static bool isValidMobile(String phoneNumber) {
    // 手机号码正则表达式
    RegExp mobileRegExp = RegExp(r'^1[3-9]\d{9}$');
    return mobileRegExp.hasMatch(phoneNumber);
  }

  /// 预售支付尾款是否已经结束
  static bool isPresaleEnded(String presaleEndTimeStr) {
    // 将 presaleEndTimeStr 字符串解析为 DateTime 对象
    DateTime presaleEndTime = DateTime.parse(presaleEndTimeStr);
    // 获取当前时间
    DateTime currentTime = DateTime.now();
    // 比较当前时间与 presaleEndTime，返回 true 如果预售已结束
    return currentTime.isAfter(presaleEndTime);
  }

  /// 活动是否结束
  static bool isActivityEnded(int endTime) {
    DateTime presaleEndTime = DateTime.fromMillisecondsSinceEpoch(endTime * 1000, isUtc: true);
    DateTime currentTime = DateTime.now().toUtc(); // 确保当前时间是 UTC 时间
    print("Presale End Time: ${presaleEndTime.toIso8601String()}");
    // 比较当前时间与 presaleEndTime，返回 true 如果预售已结束
    bool booValue = currentTime.isAfter(presaleEndTime);
    print("Presale End Time: ${booValue}");
    return booValue;
  }

  static Object formatNumber(double value) {
    // 向下取整的整数部分
    int integerPart = value.floor();
    // 判断小数部分是否为 0
    if (value == integerPart) {
      // 如果小数部分为 0，返回整数形式
      return integerPart.toString();
    } else {
      // 如果有小数部分，保留两位小数并返回
      return (value * 100).floor() / 100.0; // 处理为两位小数向下取整
    }
  }

  static String signStr() {
    // 1.nonce
    final nonce = const Uuid().v4();
    // 2.timestamp
    final timestamp = DateTime.now().millisecondsSinceEpoch.toString();
    // 3.web_token
    final webToken = '${AppData.phoneNumber ?? ''}${AppData.sid}';
    // 4.im_user_key [管理中心-即时通讯-网页插件-管理/添加客户信息中的KEY]
    const imUserKey = '31a56898dbd3caaa2bb0318ee12bf2c5';

    final baseStr = 'nonce=$nonce&timestamp=$timestamp&web_token=$webToken&$imUserKey';

    // 5.拼接
    final signString = sha1.convert(utf8.encode(baseStr)).toString();
    // 6.将字符串转换为大写
    final upperCaseSign = signString.toUpperCase();

    final finalString = '${'nonce=$nonce&timestamp=$timestamp&web_token=$webToken'}&signature=$upperCaseSign';

    return finalString;
  }
}

/// 订单状态
enum OrderStatus {
  none(-1, '未知状态'),
  canceled(0, '已取消'),
  pendingPayment(10, '待支付'),
  pendingShipment(20, '待发货'),
  shipped(30, '已发货/待收货'),
  signed(40, '已签收'),
  completed(50, '已完成');

  final int value;
  final String description;

  const OrderStatus(this.value, this.description);

  // 根据 value 获取对应的枚举
  static OrderStatus fromValue(int value) {
    return OrderStatus.values.firstWhere(
      (status) => status.value == value,
      orElse: () => OrderStatus.none, // 默认状态
    );
  }

  // 获取状态描述
  String get statusDescription => description;
}

enum RefundStatus {
  /// 1. 待审核
  pendingApproval,

  /// 2. 同意退款，退款中
  refundInProgress,

  /// 3. 拒绝申请，售后关闭
  requestRejected,

  /// 4. 退款成功
  refundSuccessful,

  /// 5. 已同意退货退款，待用户发货
  returnApprovedAwaitingUserShipment,

  /// 6. 退货退款，待平台处理
  returnAwaitingPlatformProcessing,

  /// 7. 已同意换货申请，待用户发货
  exchangeApprovedAwaitingUserShipment,

  /// 8. 拒绝换货申请，售后关闭
  exchangeRejected,

  /// 9. 买家已退货，待确认收货
  returnAwaitingConfirmation,

  /// 10. 拒绝收货，售后关闭
  returnRejected,

  /// 11. 已发货，待买家收货
  shippedAwaitingBuyerReceipt,

  /// 12. 售后成功
  afterSaleSuccessful,

  /// 13. 订单退款失败
  refundFailed,

  /// 14. 已同意补寄货物
  reshipApproved
}

extension RefundStatusExtension on RefundStatus {
  String get description {
    switch (this) {
      case RefundStatus.pendingApproval:
        return '待审核';
      case RefundStatus.refundInProgress:
        return '同意退款，退款中';
      case RefundStatus.requestRejected:
        return '拒绝申请，售后关闭';
      case RefundStatus.refundSuccessful:
        return '退款成功';
      case RefundStatus.returnApprovedAwaitingUserShipment:
        return '已同意退货退款，待用户发货';
      case RefundStatus.returnAwaitingPlatformProcessing:
        return '退货退款，待平台处理';
      case RefundStatus.exchangeApprovedAwaitingUserShipment:
        return '已同意换货申请，待用户发货';
      case RefundStatus.exchangeRejected:
        return '拒绝换货申请，售后关闭';
      case RefundStatus.returnAwaitingConfirmation:
        return '买家已退货，待确认收货';
      case RefundStatus.returnRejected:
        return '拒绝收货，售后关闭';
      case RefundStatus.shippedAwaitingBuyerReceipt:
        return '已发货，待买家收货';
      case RefundStatus.afterSaleSuccessful:
        return '售后成功';
      case RefundStatus.refundFailed:
        return '订单退款失败';
      case RefundStatus.reshipApproved:
        return '已同意补寄货物';
      default:
        return '未知状态';
    }
  }

  static RefundStatus? fromInt(int value) {
    switch (value) {
      case 1:
        return RefundStatus.pendingApproval;
      case 2:
        return RefundStatus.refundInProgress;
      case 3:
        return RefundStatus.requestRejected;
      case 4:
        return RefundStatus.refundSuccessful;
      case 5:
        return RefundStatus.returnApprovedAwaitingUserShipment;
      case 6:
        return RefundStatus.returnAwaitingPlatformProcessing;
      case 7:
        return RefundStatus.exchangeApprovedAwaitingUserShipment;
      case 8:
        return RefundStatus.exchangeRejected;
      case 9:
        return RefundStatus.returnAwaitingConfirmation;
      case 10:
        return RefundStatus.returnRejected;
      case 11:
        return RefundStatus.shippedAwaitingBuyerReceipt;
      case 12:
        return RefundStatus.afterSaleSuccessful;
      case 13:
        return RefundStatus.refundFailed;
      case 14:
        return RefundStatus.reshipApproved;
      default:
        return null; // 或抛出异常
    }
  }
}

// 随机颜色
Color getRandomColor() {
  final random = Random();
  return Color.fromARGB(
    255, // Alpha 通道设为不透明
    random.nextInt(256), // 红色通道 (0-255)
    random.nextInt(256), // 绿色通道 (0-255)
    random.nextInt(256), // 蓝色通道 (0-255)
  );
}

enum ContainerStyleType {
  noBorderWhite, // 无边白底
  cardShadow, // 卡片投影
  borderWhite, // 描边白底
  noBorderTransparent, // 无边透明
}

class DecorationProvider {
  // 根据样式类型返回 BoxDecoration
  static BoxDecoration getDecoration(ContainerStyleType type, BorderRadius borderRadius) {
    switch (type) {
      case ContainerStyleType.noBorderWhite:
        return BoxDecoration(
          color: Colors.white, // 白色背景
          border: Border.all(color: Colors.transparent), // 无边框
          borderRadius: borderRadius,
        );
      case ContainerStyleType.cardShadow:
        return BoxDecoration(
          color: Colors.white, // 白色背景
          borderRadius: borderRadius,
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.2), // 阴影颜色
              blurRadius: 10, // 阴影模糊半径
              offset: const Offset(0, 4), // 阴影偏移
            ),
          ],
        );
      case ContainerStyleType.borderWhite:
        return BoxDecoration(
          color: Colors.white, // 白色背景
          borderRadius: borderRadius,
          border: Border.all(
            color: Colors.white, // 白色边框
            width: 2, // 边框宽度
          ),
        );
      case ContainerStyleType.noBorderTransparent:
        return BoxDecoration(
          color: Colors.transparent, // 透明背景
          border: Border.all(color: Colors.transparent), // 无边框
        );
      default:
        return const BoxDecoration();
    }
  }
}

class StringGenerator {
  // 字符集合，可以根据需求调整
  static const String _chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

  /// 生成随机字符串
  /// [minLength]: 最小长度
  /// [maxLength]: 最大长度
  static String generateRandomString({int minLength = 10, int maxLength = 50}) {
    if (minLength > maxLength || minLength <= 0 || maxLength <= 0) {
      throw ArgumentError('Invalid length range: minLength should be <= maxLength and > 0.');
    }

    // 随机生成一个长度
    final length = Random().nextInt(maxLength - minLength + 1) + minLength;

    // 使用 StringBuffer 来高效拼接字符串
    final random = Random();
    final buffer = StringBuffer();
    for (int i = 0; i < length; i++) {
      buffer.write(_chars[random.nextInt(_chars.length)]);
    }
    return buffer.toString();
  }
}
